using System;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

using Abp.UI;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Linq.Extensions;


using Yozeev.BusinessLogic;
using Yozeev.BusinessLogic.Dtos;
using Yozeev.BusinessLogic.DomainService;
using Yozeev.BusinessLogic.Authorization;
using Yozeev.SystemConfig;
using Yozeev.Common;
using Microsoft.AspNetCore.Mvc;
using Abp.Authorization.Users;

namespace Yozeev.BusinessLogic
{
	/// <summary>
	/// Activity应用层服务的接口实现方法  
	///</summary>
	[AbpAuthorize]
	public class ActivityAppService : YozeevAppServiceBase, IActivityAppService
    {
        private readonly IRepository<Activity, Guid> _entityRepository;

		private readonly IRepository<Source, Guid> _sourceRepository;

		private readonly IRepository<Schedule, Guid> _scheduleRepository;

        private readonly IRepository<PayMethod, Guid> _payMethodRepository;

        private readonly IRepository<Customer, Guid> _customerRepository;

        private readonly IActivityManager _entityManager;

		private readonly IQueryHelper _queryHelper;

		/// <summary>
		/// 构造函数 
		///</summary>
		public ActivityAppService(
        IRepository<Activity, Guid> entityRepository
        ,IActivityManager entityManager
			, IRepository<Source, Guid> sourceRepository
			, IRepository<Schedule, Guid> scheduleRepository
			, IRepository<PayMethod, Guid> payMethodRepository
			, IQueryHelper queryHelper
            , IRepository<Customer, Guid> customerRepository
        )
        {
            _entityRepository = entityRepository; 
             _entityManager=entityManager;
			_scheduleRepository = scheduleRepository;
			_sourceRepository = sourceRepository;
			_queryHelper = queryHelper;
			_payMethodRepository = payMethodRepository;
            _customerRepository = customerRepository;
        }
			 
        /// <summary>
        /// 获取Activity的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
		[HttpPost]
        public async Task<PagedResultDto<ActivityListDto>> GetPaged(GetActivitysInput input)
		{
			var expression = _queryHelper.WhereExp<Activity>(input.queryData);
			if (AbpUserBase.AdminUserName != GetCurrentUser().UserName)
				expression = _queryHelper.SetWhereExp<Activity>(expression, GetViewTypeEnum<Activity>(), await GetBranchUser());
			var query = from actity in _entityRepository.GetAll().AsNoTracking().Where(expression)
                        join customer in _customerRepository.GetAll().WhereIf(!string.IsNullOrWhiteSpace( input.CertificatesNum),m=>m.CertificatesNum==input.CertificatesNum) 
						on actity.CustomerId equals customer.Id
                        join schedule in _scheduleRepository.GetAll() on actity.ScheduleId equals schedule.Id
                        select new
						{
							actity,
							actity.Source,
							actity.Account,
                            schedule,
							actity.PayMethod,
                            customer,
						};
			var list = new List<ActivityListDto>();
			query.ToList().ForEach(temp => {
				var _actity = temp.actity.MapTo<ActivityListDto>();
				_actity.Source = temp.Source;
                _actity.Schedule = temp.schedule;
				_actity.Account = temp.Account;
				_actity.PayMethod = temp.PayMethod;
                _actity.Customer = temp.customer;
				list.Add(_actity);
			});
			// TODO:根据传入的参数添加过滤条件
			var count = list.Count();
			list = list.AsQueryable().OrderBy(input.Sorting)
					.PageBy(input)
					.ToList();
			var entityList = list;
			
			var entityListDtos =entityList.MapTo<List<ActivityListDto>>();

			return new PagedResultDto<ActivityListDto>(count,entityListDtos);
		}


		/// <summary>
		/// 通过指定id获取ActivityListDto信息
		/// </summary>
		public async Task<ActivityListDto> GetById(EntityDto<Guid> input)
		{
			var entity = await _entityRepository.GetAsync(input.Id);

		    return entity.MapTo<ActivityListDto>();
		}

		/// <summary>
		/// 获取编辑 Activity
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task<GetActivityForEditOutput> GetForEdit(NullableIdDto<Guid> input)
		{
			var output = new GetActivityForEditOutput();
ActivityEditDto editDto;

			if (input.Id.HasValue)
			{
				var entity = await _entityRepository.GetAsync(input.Id.Value);

				editDto = entity.MapTo<ActivityEditDto>();

				//activityEditDto = ObjectMapper.Map<List<activityEditDto>>(entity);
			}
			else
			{
				editDto = new ActivityEditDto();
			}

			output.Activity = editDto;
			return output;
		}

		/// <summary>
		/// 添加或者修改Activity的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task CreateOrUpdate(CreateOrUpdateActivityInput input)
		{

			if (input.Activity.Id.HasValue)
			{
				await Update(input.Activity);
			}
			else
			{
				await Create(input.Activity);
			}
		}

		/// <summary>
		/// 新增Activity
		/// </summary>
		protected virtual async Task<ActivityEditDto> Create(ActivityEditDto input)
		{
			//TODO:新增前的逻辑判断，是否允许新增

            // var entity = ObjectMapper.Map <Activity>(input);
            var entity=input.MapTo<Activity>();
			

			entity = await _entityRepository.InsertAsync(entity);
			return entity.MapTo<ActivityEditDto>();
		}

		/// <summary>
		/// 编辑Activity
		/// </summary>
		protected virtual async Task Update(ActivityEditDto input)
		{
			//TODO:更新前的逻辑判断，是否允许更新

			var entity = await _entityRepository.GetAsync(input.Id.Value);
			input.MapTo(entity);

			// ObjectMapper.Map(input, entity);
		    await _entityRepository.UpdateAsync(entity);
		}

		/// <summary>
		/// 删除Activity信息的方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task Delete(EntityDto<Guid> input)
		{
			//TODO:删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(input.Id);
		}

		/// <summary>
		/// 批量删除Activity的方法
		/// </summary>
		public async Task BatchDelete(List<Guid> input)
		{
			// TODO:批量删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(s => input.Contains(s.Id));
		}

		/// <summary>
		/// 导出Activity为excel表,等待开发。
		/// </summary>
		/// <returns></returns>
		//public async Task<FileDto> GetToExcel()
		//{
		//	var users = await UserManager.Users.ToListAsync();
		//	var userListDtos = ObjectMapper.Map<List<UserListDto>>(users);
		//	await FillRoleNames(userListDtos);
		//	return _userListExcelExporter.ExportToFile(userListDtos);
		//}


		/// <summary>
		/// 销售员售票统计
		///</summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task<PagedResultDto<ActivityListDto>> GetActivity(GetActivitysInput input)
		{
			var query = _entityRepository.GetAll();
			// TODO:根据传入的参数添加过滤条件
			var count = await query.CountAsync();
			var entityList = await query
					.OrderBy(input.Sorting).AsNoTracking()
					.PageBy(input)
					.ToListAsync();
			// var entityListDtos = ObjectMapper.Map<List<ActivityListDto>>(entityList);
			var entityListDtos = entityList.MapTo<List<ActivityListDto>>();
			return new PagedResultDto<ActivityListDto>(count, entityListDtos);
		}
	}
}


